<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑排班' : '新增排班' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px" 
        v-loading="loading"
      >
        <!-- 医生信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科室" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择科室" 
                style="width: 100%"
                :disabled="isEdit"
                @change="handleDepartmentChange"
                filterable
              >
                <el-option 
                  v-for="item in departments" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生" prop="doctorId">
              <el-select 
                v-model="form.doctorId" 
                placeholder="请选择医生" 
                style="width: 100%"
                :disabled="isEdit"
                filterable
              >
                <el-option 
                  v-for="item in doctors" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 排班信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班日期" prop="date">
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择排班日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                :disabled="isEdit"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大预约数" prop="maxAppointments">
              <el-input-number
                v-model="form.maxAppointments"
                :min="0"
                :max="100"
                placeholder="不填则无限制"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="时间段" prop="timeSlots">
          <div class="time-slots-container">
            <el-checkbox-group v-model="form.timeSlots">
              <el-checkbox-button 
                v-for="slot in timeSlotOptions" 
                :key="slot.value" 
                :label="slot.value"
              >
                {{ slot.label }}
              </el-checkbox-button>
            </el-checkbox-group>
          </div>
          <div class="form-tips">
            选择医生在该日期可出诊的时间段
          </div>
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input 
            v-model="form.notes" 
            type="textarea" 
            placeholder="请输入备注信息（可选）" 
            :rows="3"
          />
        </el-form-item>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { scheduleAPI } from '@/utils/api'
import { getDepartmentOptions, getDoctorOptions } from '@/utils/formData'

// 路由实例
const router = useRouter()
const route = useRoute()

// 判断是编辑还是新增
const isEdit = computed(() => route.params.id !== undefined)

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  departmentId: '',
  doctorId: '',
  date: '',
  timeSlots: [],
  maxAppointments: undefined,
  notes: ''
})

// 选项数据
const departments = ref([])
const doctors = ref([])

// 时间段选项
const timeSlotOptions = [
  { label: '08:00-09:00', value: '08:00-09:00' },
  { label: '09:00-10:00', value: '09:00-10:00' },
  { label: '10:00-11:00', value: '10:00-11:00' },
  { label: '11:00-12:00', value: '11:00-12:00' },
  { label: '14:00-15:00', value: '14:00-15:00' },
  { label: '15:00-16:00', value: '15:00-16:00' },
  { label: '16:00-17:00', value: '16:00-17:00' },
  { label: '17:00-18:00', value: '17:00-18:00' }
]

// 表单验证规则
const rules = {
  departmentId: [
    { required: true, message: '请选择科室', trigger: 'change' }
  ],
  doctorId: [
    { required: true, message: '请选择医生', trigger: 'change' }
  ],
  date: [
    { required: true, message: '请选择排班日期', trigger: 'change' }
  ],
  timeSlots: [
    { required: true, message: '请至少选择一个时间段', trigger: 'change' }
  ]
}

// 禁用的日期（今天之前的日期不可选）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 获取科室列表
const fetchDepartments = async () => {
  try {
    departments.value = await getDepartmentOptions()
  } catch (error) {
    console.error('获取科室列表失败', error)
    ElMessage.error('获取科室列表失败，请刷新页面重试')
  }
}

// 处理科室选择变化
const handleDepartmentChange = async () => {
  form.doctorId = ''
  doctors.value = []
  
  if (!form.departmentId) return
  
  try {
    doctors.value = await getDoctorOptions(form.departmentId)
  } catch (error) {
    console.error('获取医生列表失败', error)
    ElMessage.error('获取医生列表失败，请刷新页面重试')
  }
}

// 获取排班详情
const getScheduleDetail = async () => {
  loading.value = true
  try {
    const res = await scheduleAPI.getSchedule(route.params.id)
    if (res.success && res.data) {
      // 填充表单数据
      const scheduleData = res.data
      
      form.departmentId = scheduleData.departmentId
      form.doctorId = scheduleData.doctorId
      form.date = scheduleData.date.split('T')[0]
      form.notes = scheduleData.notes || ''
      form.maxAppointments = scheduleData.maxAppointments
      
      // 处理时间段
      if (scheduleData.timeSlots && Array.isArray(scheduleData.timeSlots)) {
        form.timeSlots = scheduleData.timeSlots.map(slot => {
          if (typeof slot === 'string') {
            return slot
          } else if (slot.startTime && slot.endTime) {
            return `${slot.startTime}-${slot.endTime}`
          }
          return null
        }).filter(Boolean)
      }
      
      // 获取医生列表
      await handleDepartmentChange()
    }
  } catch (error) {
    console.error('获取排班详情失败', error)
    ElMessage.error('获取排班详情失败，请返回重试')
  } finally {
    loading.value = false
  }
}

// 检查排班冲突
const checkScheduleConflict = async () => {
  try {
    const params = {
      doctorId: form.doctorId,
      date: form.date
    }
    if (isEdit.value) {
      params.excludeId = route.params.id
    }
    
    const res = await scheduleAPI.getSchedules(params)
    
    if (res.data.items && res.data.items.length > 0) {
      // 已有排班，检查时间段是否有冲突
      const existingSchedule = res.data.items[0]
      const existingSlots = existingSchedule.timeSlots || []
      
      // 检查是否有重叠的时间段
      const conflictSlots = form.timeSlots.filter(slot => existingSlots.includes(slot))
      
      if (conflictSlots.length > 0) {
        ElMessage.warning(`该医生在所选日期的以下时间段已有排班：${conflictSlots.join('、')}`)
        return false
      }
    }
    
    return true
  } catch (error) {
    console.error('检查排班冲突失败', error)
    ElMessage.error('检查排班冲突失败')
    return false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.log('表单验证失败', fields)
      return
    }
    
    submitLoading.value = true
    try {
      // 准备提交数据
      const submitData = {
        departmentId: form.departmentId,
        doctorId: form.doctorId,
        date: form.date,
        timeSlots: form.timeSlots,
        notes: form.notes
      }
      
      if (form.maxAppointments !== undefined && form.maxAppointments !== null) {
        submitData.maxAppointments = form.maxAppointments
      }
      
      // 执行创建或更新操作
      let res
      if (isEdit.value) {
        res = await scheduleAPI.updateSchedule(route.params.id, submitData)
      } else {
        res = await scheduleAPI.createSchedule(submitData)
      }
      
      if (res.success) {
        ElMessage.success(isEdit.value ? '排班更新成功' : '排班创建成功')
        goBack()
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    } catch (error) {
      console.error('提交排班数据失败', error)
      ElMessage.error(error.message || '提交失败，请重试')
    } finally {
      submitLoading.value = false
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/schedules')
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchDepartments()
  
  if (isEdit.value) {
    await getScheduleDetail()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-slots-container {
  margin-bottom: 10px;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 